#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include "../../src/stack/lockfree_stack.h"

#define NUM_THREADS 4
#define OPS_PER_THREAD 100000

stack_t stack;
atomic_int push_count = 0;
atomic_int pop_count = 0;

void* worker(void* arg) {
    int thread_id = *(int*)arg;
    
    // 每个线程交替进行push和pop操作
    for (int i = 0; i < OPS_PER_THREAD; i++) {
        if (i % 2 == 0) {
            // Push操作
            int* value = malloc(sizeof(int));
            *value = i;
            if (stack_push(&stack, value)) {
                atomic_fetch_add(&push_count, 1, memory_order_relaxed);
            }
        } else {
            // Pop操作
            void* data = stack_pop(&stack);
            if (data) {
                free(data);
                atomic_fetch_add(&pop_count, 1, memory_order_relaxed);
            }
        }
    }
    return NULL;
}

int main() {
    pthread_t threads[NUM_THREADS];
    int thread_ids[NUM_THREADS];
    struct timespec start, end;
    
    stack_init(&stack);
    clock_gettime(CLOCK_MONOTONIC, &start);
    
    // 创建线程
    for (int i = 0; i < NUM_THREADS; i++) {
        thread_ids[i] = i;
        pthread_create(&threads[i], NULL, worker, &thread_ids[i]);
    }
    
    // 等待所有线程完成
    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }
    
    clock_gettime(CLOCK_MONOTONIC, &end);
    
    double time_spent = (end.tv_sec - start.tv_sec) +
                       (end.tv_nsec - start.tv_nsec) / 1e9;
    
    printf("Time spent: %.2f seconds\n", time_spent);
    printf("Operations per second: %.2f\n", 
           (NUM_THREADS * OPS_PER_THREAD) / time_spent);
    printf("Total pushes: %d\n", atomic_load(&push_count, memory_order_relaxed));
    printf("Total pops: %d\n", atomic_load(&pop_count, memory_order_relaxed));
    
    // 清理剩余的节点
    while (!stack_is_empty(&stack)) {
        void* data = stack_pop(&stack);
        if (data) free(data);
    }
    
    return 0;
} 